import heapq
import collections
class Solution(object):
    def repeatLimitedString(self, s, repeatLimit):
        c = collections.Counter(s)
        st = [[ord('a') - ord(key), c[key]] for key in c]
        heapq.heapify(st)
        ans = []
        while st:
            x, num = heapq.heappop(st)
            if num <= repeatLimit:
                ans.append(chr(ord('a') - x) * num)
            else:
                ans.append(chr(ord('a') - x) * repeatLimit)
                if st:
                    y, num2 = heapq.heappop(st)
                    ans.append(chr(ord('a') - y))
                    num2 -= 1
                    if num2 > 0:
                        heapq.heappush(st, [y, num2])
                    heapq.heappush(st, [x, num - repeatLimit])
        return ''.join(ans)

data = Solution()
s = "cczazcc"
repeatLimit = 3
print(data.repeatLimitedString(s, repeatLimit))
